package cn.rxls.community.controller;


import cn.rxls.community.entity.User;
import cn.rxls.community.enums.ResultEnum;
import cn.rxls.community.exception.BusinessException;
import cn.rxls.community.result.Result;
import cn.rxls.community.service.UserService;
import cn.rxls.community.util.HttpUtil;
import cn.rxls.community.util.StrFileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;

/**
 * 用户(User)表
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 配置文件中配置文件保存的路径
     */
    @Value("${img.location}")
    private String folder;


    /**
     * 上传、更新头像
     *
     * @param request Http 对象
     * @param file    文件
     * @return 文件路径
     */
    @PostMapping("/imgUpload")
    public Result<String> imageUpload(HttpServletRequest request, @RequestParam(value = "image_file", required = false) MultipartFile file) throws IOException {
        //获取用户信息，判定是否合法
        Map<String, Object> userLoginInfo = HttpUtil.getUserLoginInfo();
        Optional.ofNullable(userLoginInfo).orElseThrow(() -> new BusinessException(ResultEnum.ERROR_LOGIN));

        Optional.ofNullable(file).orElseThrow(() -> new BusinessException(ResultEnum.ERROR_UPLOAD_IMG_TYPE));

        //如果上传文件不为空
        if (!file.isEmpty()) {
            String filename = file.getOriginalFilename();//获取文件名
            //是否是一个文件
            Optional.ofNullable(filename).orElseThrow(() -> new BusinessException(ResultEnum.ERROR_UPLOAD_IMG_TYPE));
            //获取文件后缀
            String intercept = StrFileUtil.intercept(filename, '.');

            //最终图片存储的名称
            String fileUrl = "rxzf-image-a" + userLoginInfo.get("userId") + intercept;
            //写入本地
            file.transferTo(new File(folder + fileUrl));
            //项目的端口号http://localhost:8942
            String basePath = request.getScheme()//获取协议号
                    + "://"
                    + request.getServerName()//获取IP地址
                    + ":"
                    + request.getServerPort()//获取端口号
                    + request.getContextPath();//获取工程路径
            //图片访问路径,用户id一起拼接
            String avatarUrl = basePath + "/upload/" + fileUrl;

            //用户头像更新
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            User newUser = new User();
            wrapper.eq(User::getUserId, userLoginInfo.get("userId"));
            newUser.setAvatar(avatarUrl);
            userService.update(newUser, wrapper);
            return Result.success(avatarUrl);
        }
        return Result.error(ResultEnum.ERROR_UPLOAD_AVATAR);
    }


}

